# -*- coding: utf-8 -*-

#    Copyright (C) 2005-2013 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of Promogest.

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.


from web_lib.page import Page
from web_lib.webutils import Response, expose
from web_lib.MailHandler import SendMail
from promogest.dao.User import User


@expose('/recoveryPassword')
def recoverypassword(req,static=None, subdomain=None):
    """ funzione di recupero password
    TODO: aggiungere il prima possibile il captcha
    """
    #    captcha = req.form.get('captcha')
    #    string = req.form.get('string')
    if req.form.get('username') and not req.form.get('emailrecovery'):
        error = """Indirizzo email mancante"""
        pageData = {'file' : 'main/recoveryPassword',
                    'error' : error}
        return Page(req).render(pageData)
    elif req.form.get('username') and req.form.get('emailrecovery'):
        user = User().select(username=req.form.get('username'),
                        email=req.form.get('emailrecovery'))
        if not user:
            error = """Qualche dato utente mancante o inesatto.<br />
                Ricontrolla username o indirizzo email"""
            pageData = {'file' : 'main/recoveryPassword',
                        'error' : error}
            return Page(req).render(pageData)
        else:
            #newpasswd = createRandomString()
            newpasswd = user[0].password
            error = """La sua Password è stata inviata all'indirizzo email da lei inserito"""
            pageData = {'file' : 'main/recoveryPassword',
                        "error":error,
                        "subdomain": subdomain}
            SendMail(req,
                    to=req.form.get('emailrecovery')).sendRecoveryPassword(newpasswd = newpasswd)
    else:
        pageData = {'file' : 'main/recoveryPassword',
                    "subdomain": subdomain}
    return Page(req).render(pageData)
